package com.my.transaction;

import com.my.user.util.DataSourceUtils;

import java.sql.Connection;
import java.sql.SQLException;

public class JDBCUtil {
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    public static Connection getConnection() throws SQLException {
        Connection conn = threadLocal.get();
        if(conn==null){
            conn = DataSourceUtils.getDataSourceWithC3P0ByXML().getConnection();
            threadLocal.set(conn);
        }
        return conn;
    }

    //开启事务
    public static void beginTransaction() throws SQLException {
        Connection conn = getConnection();
        conn.setAutoCommit(false);
    }

    //正常，提交事务
    public static void commitTransaction() throws SQLException {
        Connection conn = getConnection();
        if(conn!=null)
            conn.commit();
    }

    //失败，回滚事务
    public static void rollbackTransaction() throws SQLException {
        Connection conn = getConnection();
        if(conn!=null)
            conn.rollback();
    }

    //关闭连接
    public static void close() throws SQLException {
        Connection conn = getConnection();
        if(conn!=null)
            conn.close();
        threadLocal.remove();
        conn=null;
    }
}
